import { ref, reactive, watch, toRefs } from 'vue';
import { useStore } from 'vuex';
import { logOut } from '@/common/api/user.js';
import { showModal } from './useShow.js';
export default function(wxLogin) {
	const store = useStore();
	const data = reactive({
		isLogin: store.getters.token && store.getters.userInfo.mid ? 1 : 0
	});
	// 判断是否登录后跳转
	const navToCheckLogin = async (url) => {
		const token = store.getters.token && store.getters.userInfo.mid;
		if (!token) {
			await wxLogin.value.init();
			return false;
		}
		if (url) uni.navigateTo({
			url
		})
		return true;
	}
	// 退出登录
	const loginOut = () => {
		showModal({
			title: '提示',
			content: '确认退出?',
			confirm() {
				logOut().then(() => {
					store.commit('user/REMOVE_TOKEN');
					setTimeout(() => {
						uni.navigateBack();
					}, 200)
				})
			}
		})
	}
	// 切换角色
	const toogleRole = () => {
		const role = store.getters.role;
		switch (role) {
			case 'user':
				if (!store.getters.userInfo.is_merchant) return showModal({
					title: '提示',
					content: '成为行业大牛(商户)即可切换角色',
					confirmText: '入驻开通',
					confirm() {
						uni.navigateTo({
							url: '/subpages/user-merchant/open/open'
						})
					}
				})
				showModal({
					title: '提示',
					content: '从"普通用户"切换为"商家用户"角色？',
					confirm() {
						store.commit('user/SET_ROLE', 'merchant');
						uni.showToast({
							icon: 'success',
							title: '切换成功'
						})
						setTimeout(() => {
							uni.navigateBack();
						}, 200)
					}
				})
				break;
			default:
				showModal({
					title: '提示',
					content: '从"商家用户"切换为"普通用户"角色？',
					confirm() {
						store.commit('user/SET_ROLE', 'user');
						uni.showToast({
							icon: 'success',
							title: '切换成功'
						})
						setTimeout(() => {
							uni.navigateBack();
						}, 200)
					}
				})
				break;
		}
	}
	// 去认证
	const goAuth = () => {
		// 跳转小程序
		uni.navigateToMiniProgram({
			appId: 'wx42fd2c9c759f7f59',
			path: `/subpages/user/auth/auth?token=${store.getters.token}`,
			envVersion: 'release',
			success() {},
			fail() {}
		});
	}
	// 去聊天
	const toIm = async (mid, nickname) => {
		navToCheckLogin(`/subpages/chat/chat?conversationID=${mid}&nick=${encodeURIComponent(nickname)}`);
	}
	return {
		navToCheckLogin,
		loginOut,
		toogleRole,
		goAuth,
		toIm,
		...toRefs(data)
	}
}
